package client

import (
	"encoding/json"
	"fmt"
	"gin-epg/internal/app/client/utils"
	"gin-epg/internal/app/common/util"
	"gin-epg/internal/app/dao"
	"net/url"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/spf13/cast"
)

/*
 *列表
http://hntvepg.taipan.jda.bcs.ottcn.com:8080/ysten-lvoms-epg/epg/getChannels.shtml?templateId=0734&districtCode=430000
当前
http://hntvepg.taipan.jda.bcs.ottcn.com:8080/ysten-lvoms-epg/epg/getNewPrograms.shtml?catgId=371&actionType=OpenNew&deviceGroupId=177&districtCode=430000&templateId=0734&random=0.00161108304746449
当天 (默认返回7填)
http://hntvepg.taipan.jda.bcs.ottcn.com:8080/ysten-lvoms-epg/epg/getAllDayPrograms.shtml?actionType=OpenNew&deviceGroupId=177&uuid=SD-1500k-576P-hnjingshi
*/
/*
 * deviceGroupId 备选
177 413 1093 2663 3570 3859 3911 3939 4248 4268
4336 4430 4468 4532 4538 4681 4733 4738 4787 4794
4935 4936 5038 5064 5084 5100 5104 5106 5110 5185
5189 5202 5219 5220 5241 5258 5262 5263 5264 5265
5286 5288 5289 5311 5313 5321 5324 5349 5369 5371
5387 5394 5396 5406 5410 5411 5440 5441 5449 5479
5495 5497 5499 5514 5523 5529 5533 5536 5537 5556
5564 5568 5595 5597 5598 5599 5607 5620 5674 5677
5690 5691 5703 5723 5729 5743 5858 5868 5870 5871
5872 5881 5885 5886 5896 5907 5909 5920 5933 5934
5935 5937 5940 5954 5955 5959 5960 5961 5967 5971
5975 5977 5978 5982 5983 5984 5985 5989 5990 5994
5995 5996 6003 6004 6005 6006 6011 6012 6013 6041
6043 6049 6055 6059 6063 6066 6068 6069 6071 6072
6074 6075 6076 6082 6083 6084 6085 6087 6094 6096
6097 6098 6099 6100 6139 6140
*/
/*
 * 部分可能的id
湖南都市,HD-8000k-1080P-hunandushi
湖南电影,HD-8000k-1080P-xiaoxiangdy SD-1500k-576P-xiaoxiangdy
湖南电视剧,HD-8000k-1080P-xiaoxiangdsj
湖南爱晚,HD-8000k-1080P-hunangg
湖南经视高清,HD-8000k-1080P-hunanjingshi
益阳新闻 hnyiyangxw
益阳公共 hnyiyanggg
newtv魅力潇湘 SD-1500k-576P-meilixiaoxiang
*/
// 映射湖南频道ID到频道名称
var mapYstenHunan = map[string]string{
	"hdcctv-1":                  "CCTV1",
	"hdhunantv1":                "湖南卫视", // 备选id hunanstv
	"SD-1500k-576P-hnjingshi":   "湖南经视",
	"HD-8000k-1080P-hunandushi": "湖南都市",
	"HD-8000k-1080P-hunangg":    "湖南爱晚",
	"D-8000k-1080P-hunanjy":     "湖南教育",
	"SD-1500k-576P-hndianshiju": "湖南电视剧",
	"SD-1500k-576P-xiaoxiangdy": "湖南电影",
	// 更多键值对...
}

// HandleYstenHunanCron 处理易视腾湖南节目单
func HandleYstenHunanCron() error {
	dao.Logger.Infof("HandleYstenHunanCron start")
	date := time.Now().Format("20060102")
	dao.Logger.Infof(date)
	source := "ystenhunan"

	client := resty.New()
	for key, value := range mapYstenHunan {
		dao.Logger.Infof("Key: %s, Value: %s", key, value)
		// 构建URL参数
		params := url.Values{}
		params.Add("uuid", key)
		params.Add("actionType", "OpenNew")
		params.Add("deviceGroupId", "4336")

		// 编码参数
		encodedParams := params.Encode()

		// 构建完整URL
		url := fmt.Sprintf("http://hntvepg.taipan.jda.bcs.ottcn.com:8080/ysten-lvoms-epg/epg/getAllDayPrograms.shtml?%s", encodedParams)

		proxyURL, err := util.GetConfigValue("proxy.proxyApiUrlYstenhunan")
		if err != nil {
			dao.Logger.Errorf("Error: %v", err)
		} else {
			dao.Logger.Infof("proxyApiUrlYstenhunan: %v", proxyURL)
			url = fmt.Sprintf("%s%s", proxyURL, url[len("http://hntvepg.taipan.jda.bcs.ottcn.com:8080"):])
		}

		resp, err := client.R().
			SetHeaders(map[string]string{
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
			}).
			Get(url)

		if err != nil {
			return fmt.Errorf("failed to get data from URL: %v", err)
		}

		var days []map[string]interface{}
		if err := json.Unmarshal(resp.Body(), &days); err != nil {
			return fmt.Errorf("failed to unmarshal JSON: %v", err)
		}

		for _, day := range days {
			if programs, ok := day["programs"].([]interface{}); ok {
				for _, program := range programs {
					programMap := program.(map[string]interface{})
					startTime := cast.ToInt64(programMap["startTime"])
					endTime := cast.ToInt64(programMap["endTime"])
					momentStartDate := time.Unix(startTime, 0)
					momentStopDate := time.Unix(endTime, 0)

					title := cast.ToString(programMap["programName"])
					desc := ""

					db := dao.SqlSession
					utils.HandleCrossDayRecord(db, momentStartDate, momentStopDate, title, desc, value, source)
				}
			}
		}
	}
	return nil
}
